<template>
  <div class="login-container">
    <!-- 全屏科技背景 -->
    <div class="tech-background">
      <canvas ref="techCanvas" class="tech-canvas"></canvas>
      <div class="tech-overlay">
        <div class="tech-grid"></div>
        <div class="tech-particles"></div>
      </div>
    </div>

    <!-- 浮动登录表单 -->
    <div class="login-form-wrapper">
      <div class="login-form-container">
        <div class="login-header">
          <h2>{{ isLogin ? 'DevOps自动化运维' : '用户注册' }}</h2>
        </div>

        <!-- 登录表单 -->
        <el-form
          v-if="isLogin"
          ref="loginFormRef"
          :model="loginForm"
          :rules="loginRules"
          class="login-form"
          @submit.prevent="handleLogin"
        >
          <el-form-item prop="username">
            <el-input
              v-model="loginForm.username"
              placeholder="请输入用户名"
              size="large"
              prefix-icon="User"
            />
          </el-form-item>

          <el-form-item prop="password">
            <el-input
              v-model="loginForm.password"
              type="password"
              placeholder="请输入密码"
              size="large"
              prefix-icon="Lock"
              show-password
            />
          </el-form-item>

          <el-form-item>
            <el-button
              type="primary"
              size="large"
              class="login-btn"
              :loading="loading"
              @click="handleLogin"
            >
              {{ loading ? '登录中...' : '登录' }}
            </el-button>
          </el-form-item>
        </el-form>

        <!-- 注册表单 -->
        <el-form
          v-else
          ref="registerFormRef"
          :model="registerForm"
          :rules="registerRules"
          class="login-form"
          @submit.prevent="handleRegister"
        >
          <el-form-item prop="username">
            <el-input
              v-model="registerForm.username"
              placeholder="请输入用户名"
              size="large"
              prefix-icon="User"
            />
          </el-form-item>

          <el-form-item prop="email">
            <el-input
              v-model="registerForm.email"
              placeholder="请输入邮箱"
              size="large"
              prefix-icon="Message"
            />
          </el-form-item>

          <el-form-item prop="phone">
            <el-input
              v-model="registerForm.phone"
              placeholder="请输入手机号（可选）"
              size="large"
              prefix-icon="Phone"
            />
          </el-form-item>

          <el-form-item prop="password">
            <el-input
              v-model="registerForm.password"
              type="password"
              placeholder="请输入密码"
              size="large"
              prefix-icon="Lock"
              show-password
            />
          </el-form-item>

          <el-form-item prop="password_confirm">
            <el-input
              v-model="registerForm.password_confirm"
              type="password"
              placeholder="请确认密码"
              size="large"
              prefix-icon="Lock"
              show-password
            />
          </el-form-item>

          <el-form-item>
            <el-button
              type="primary"
              size="large"
              class="login-btn"
              :loading="loading"
              @click="handleRegister"
            >
              {{ loading ? '注册中...' : '注册' }}
            </el-button>
          </el-form-item>
        </el-form>

        <div class="form-footer">
          <el-button type="text" @click="toggleForm">
            {{ isLogin ? '没有账户？立即注册' : '已有账户？立即登录' }}
          </el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, type FormInstance } from 'element-plus'

import { useAuthStore } from '@/stores/auth'

const router = useRouter()
const authStore = useAuthStore()

// Canvas引用
const techCanvas = ref(null)

// 科技动画效果
onMounted(() => {
  initTechAnimation()
})

const initTechAnimation = () => {
  const canvas = techCanvas.value
  if (!canvas) return

  const ctx = canvas.getContext('2d')

  // 设置canvas尺寸
  const resizeCanvas = () => {
    const container = canvas.parentElement
    canvas.width = container.offsetWidth
    canvas.height = container.offsetHeight
  }

  resizeCanvas()
  window.addEventListener('resize', resizeCanvas)

  // 科技元素配置
  const nodes = []
  const connections = []
  const pulses = []
  const dataStreams = []
  const hexagons = []

  const nodeCount = 60
  const hexCount = 15

  // 创建网络节点
  for (let i = 0; i < nodeCount; i++) {
    nodes.push({
      x: Math.random() * canvas.width,
      y: Math.random() * canvas.height,
      vx: (Math.random() - 0.5) * 0.5,
      vy: (Math.random() - 0.5) * 0.5,
      size: Math.random() * 4 + 2,
      pulse: Math.random() * Math.PI * 2,
      pulseSpeed: Math.random() * 0.02 + 0.01,
      type: Math.random() > 0.7 ? 'core' : 'normal', // 核心节点更亮
      energy: Math.random()
    })
  }

  // 创建六边形装饰
  for (let i = 0; i < hexCount; i++) {
    hexagons.push({
      x: Math.random() * canvas.width,
      y: Math.random() * canvas.height,
      size: Math.random() * 30 + 20,
      rotation: Math.random() * Math.PI * 2,
      rotationSpeed: (Math.random() - 0.5) * 0.01,
      opacity: Math.random() * 0.3 + 0.1,
      strokeWidth: Math.random() * 2 + 1
    })
  }

  // 创建数据流
  const createDataStream = () => {
    if (nodes.length < 2) return

    const startNode = nodes[Math.floor(Math.random() * nodes.length)]
    const endNode = nodes[Math.floor(Math.random() * nodes.length)]

    if (startNode === endNode) return

    dataStreams.push({
      startX: startNode.x,
      startY: startNode.y,
      endX: endNode.x,
      endY: endNode.y,
      progress: 0,
      speed: Math.random() * 0.02 + 0.01,
      life: 1,
      size: Math.random() * 3 + 2
    })
  }

  // 定期创建数据流
  setInterval(createDataStream, 800)

  // 动画循环
  const animate = () => {
    // 半透明清除，创建拖尾效果
    ctx.fillStyle = 'rgba(12, 20, 38, 0.1)'
    ctx.fillRect(0, 0, canvas.width, canvas.height)

    // 绘制六边形装饰
    hexagons.forEach(hex => {
      hex.rotation += hex.rotationSpeed

      ctx.save()
      ctx.translate(hex.x, hex.y)
      ctx.rotate(hex.rotation)

      // 绘制六边形
      ctx.beginPath()
      for (let i = 0; i < 6; i++) {
        const angle = (i * Math.PI) / 3
        const x = Math.cos(angle) * hex.size
        const y = Math.sin(angle) * hex.size
        if (i === 0) ctx.moveTo(x, y)
        else ctx.lineTo(x, y)
      }
      ctx.closePath()
      ctx.strokeStyle = `rgba(0, 150, 255, ${hex.opacity})`
      ctx.lineWidth = hex.strokeWidth
      ctx.stroke()

      ctx.restore()
    })

    // 更新和绘制节点
    nodes.forEach(node => {
      // 更新位置
      node.x += node.vx
      node.y += node.vy
      node.pulse += node.pulseSpeed

      // 边界检测
      if (node.x < 0 || node.x > canvas.width) node.vx *= -1
      if (node.y < 0 || node.y > canvas.height) node.vy *= -1

      // 脉冲效果
      const pulseScale = 1 + Math.sin(node.pulse) * 0.3
      const nodeSize = node.size * pulseScale

      // 绘制节点光晕
      const gradient = ctx.createRadialGradient(node.x, node.y, 0, node.x, node.y, nodeSize * 3)
      if (node.type === 'core') {
        gradient.addColorStop(0, 'rgba(100, 200, 255, 0.8)')
        gradient.addColorStop(0.3, 'rgba(0, 150, 255, 0.4)')
        gradient.addColorStop(1, 'rgba(0, 150, 255, 0)')
      } else {
        gradient.addColorStop(0, 'rgba(100, 200, 255, 0.6)')
        gradient.addColorStop(0.5, 'rgba(100, 200, 255, 0.2)')
        gradient.addColorStop(1, 'rgba(100, 200, 255, 0)')
      }

      ctx.beginPath()
      ctx.arc(node.x, node.y, nodeSize * 3, 0, Math.PI * 2)
      ctx.fillStyle = gradient
      ctx.fill()

      // 绘制节点核心
      ctx.beginPath()
      ctx.arc(node.x, node.y, nodeSize, 0, Math.PI * 2)
      ctx.fillStyle = node.type === 'core' ? 'rgba(255, 255, 255, 0.9)' : 'rgba(100, 200, 255, 0.8)'
      ctx.fill()
    })

    // 绘制节点连接线
    for (let i = 0; i < nodes.length; i++) {
      for (let j = i + 1; j < nodes.length; j++) {
        const dx = nodes[i].x - nodes[j].x
        const dy = nodes[i].y - nodes[j].y
        const distance = Math.sqrt(dx * dx + dy * dy)

        if (distance < 120) {
          const alpha = (1 - distance / 120) * 0.4
          const lineWidth = (1 - distance / 120) * 2

          // 创建连接线渐变
          const gradient = ctx.createLinearGradient(nodes[i].x, nodes[i].y, nodes[j].x, nodes[j].y)
          gradient.addColorStop(0, `rgba(100, 200, 255, ${alpha})`)
          gradient.addColorStop(0.5, `rgba(0, 150, 255, ${alpha * 1.5})`)
          gradient.addColorStop(1, `rgba(100, 200, 255, ${alpha})`)

          ctx.beginPath()
          ctx.moveTo(nodes[i].x, nodes[i].y)
          ctx.lineTo(nodes[j].x, nodes[j].y)
          ctx.strokeStyle = gradient
          ctx.lineWidth = lineWidth
          ctx.stroke()
        }
      }
    }

    // 更新和绘制数据流
    dataStreams.forEach((stream, index) => {
      stream.progress += stream.speed
      stream.life -= 0.005

      if (stream.progress >= 1 || stream.life <= 0) {
        dataStreams.splice(index, 1)
        return
      }

      // 计算当前位置
      const currentX = stream.startX + (stream.endX - stream.startX) * stream.progress
      const currentY = stream.startY + (stream.endY - stream.startY) * stream.progress

      // 绘制数据流粒子
      const alpha = stream.life * 0.8
      const size = stream.size * stream.life

      // 粒子光晕
      const gradient = ctx.createRadialGradient(currentX, currentY, 0, currentX, currentY, size * 2)
      gradient.addColorStop(0, `rgba(255, 255, 255, ${alpha})`)
      gradient.addColorStop(0.5, `rgba(100, 200, 255, ${alpha * 0.6})`)
      gradient.addColorStop(1, `rgba(100, 200, 255, 0)`)

      ctx.beginPath()
      ctx.arc(currentX, currentY, size * 2, 0, Math.PI * 2)
      ctx.fillStyle = gradient
      ctx.fill()

      // 粒子核心
      ctx.beginPath()
      ctx.arc(currentX, currentY, size, 0, Math.PI * 2)
      ctx.fillStyle = `rgba(255, 255, 255, ${alpha})`
      ctx.fill()
    })

    requestAnimationFrame(animate)
  }

  animate()
}

const isLogin = ref(true)
const loading = ref(false)
const loginFormRef = ref<FormInstance>()
const registerFormRef = ref<FormInstance>()

// 登录表单
const loginForm = reactive({
  username: '',
  password: ''
})

// 注册表单
const registerForm = reactive({
  username: '',
  email: '',
  phone: '',
  password: '',
  password_confirm: ''
})

// 登录表单验证规则
const loginRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ]
}

// 注册表单验证规则
const registerRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度在3到20个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ],
  password_confirm: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    {
      validator: (rule: any, value: string, callback: Function) => {
        if (value !== registerForm.password) {
          callback(new Error('两次输入密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 切换登录/注册表单
const toggleForm = () => {
  isLogin.value = !isLogin.value
  // 清空表单
  if (isLogin.value) {
    Object.assign(loginForm, { username: '', password: '' })
  } else {
    Object.assign(registerForm, {
      username: '',
      email: '',
      phone: '',
      password: '',
      password_confirm: ''
    })
  }
}

// 处理登录
const handleLogin = async () => {
  if (!loginFormRef.value) return
  
  await loginFormRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true
      try {
        const result = await authStore.login(loginForm.username, loginForm.password)
        if (result.success) {
          ElMessage.success('登录成功')
          router.push('/')
        } else {
          ElMessage.error(result.message || '登录失败')
        }
      } finally {
        loading.value = false
      }
    }
  })
}

// 处理注册
const handleRegister = async () => {
  if (!registerFormRef.value) return
  
  await registerFormRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true
      try {
        const result = await authStore.register(registerForm)
        if (result.success) {
          ElMessage.success('注册成功，请登录')
          isLogin.value = true
          Object.assign(loginForm, { username: registerForm.username, password: '' })
        } else {
          ElMessage.error(result.message || '注册失败')
        }
      } finally {
        loading.value = false
      }
    }
  })
}
</script>

<style scoped>
.login-container {
  position: relative;
  width: 100%;
  height: 100vh;
  overflow: hidden;
}



/* 全屏科技背景 */
.tech-background {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background:
    radial-gradient(circle at 20% 80%, rgba(0, 150, 255, 0.1) 0%, transparent 50%),
    radial-gradient(circle at 80% 20%, rgba(100, 200, 255, 0.08) 0%, transparent 50%),
    radial-gradient(circle at 40% 40%, rgba(0, 100, 200, 0.05) 0%, transparent 50%),
    linear-gradient(135deg, #0c1426 0%, #1a2332 25%, #2d3748 50%, #1a2332 75%, #0c1426 100%);
  z-index: 1;
}

/* 浮动登录表单容器 */
.login-form-wrapper {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 40px;
  z-index: 10;
}





.login-form-container {
  width: 100%;
  max-width: 420px;
  background: transparent;
  padding: 45px;
  border-radius: 16px;
  border: none;
  position: relative;
  backdrop-filter: blur(5px);
  animation: formFloat 6s ease-in-out infinite;
}

@keyframes formFloat {
  0%, 100% {
    transform: translateY(0px);
  }
  50% {
    transform: translateY(-5px);
  }
}









.login-header {
  text-align: center;
  margin-bottom: 40px;
}

.login-header h2 {
  color: rgba(255, 255, 255, 0.95);
  margin-bottom: 0;
  font-size: 28px;
  font-weight: 600;
  text-shadow: 0 0 10px rgba(100, 200, 255, 0.3);
}

.login-form {
  margin-bottom: 20px;
}

.login-btn {
  width: 100%;
  height: 45px;
  font-size: 16px;
  font-weight: 500;
  border-radius: 8px;
  background: transparent;
  border: 1px solid rgba(100, 200, 255, 0.6);
  color: rgba(255, 255, 255, 0.95) !important;
  transition: all 0.3s ease;
}

.login-btn:hover {
  background: rgba(100, 200, 255, 0.1) !important;
  border-color: rgba(100, 200, 255, 0.8) !important;
  transform: translateY(-1px);
}

.form-footer {
  text-align: center;
}

.form-footer .el-button--text {
  color: rgba(100, 200, 255, 0.9) !important;
  font-weight: 500;
}

.form-footer .el-button--text:hover {
  color: rgba(255, 255, 255, 1) !important;
  text-shadow: 0 0 8px rgba(100, 200, 255, 0.6);
}

/* 输入框样式优化 */
.login-form .el-input__wrapper {
  background-color: transparent !important;
  border: 1px solid rgba(255, 255, 255, 0.2) !important;
  border-radius: 8px !important;
  transition: all 0.3s ease;
}

.login-form .el-input__wrapper:hover {
  border-color: rgba(255, 255, 255, 0.3) !important;
}

.login-form .el-input__wrapper.is-focus {
  border-color: rgba(100, 200, 255, 0.6) !important;
}

.login-form .el-input__inner {
  color: rgba(255, 255, 255, 0.9) !important;
  background-color: transparent !important;
}

.login-form .el-input__inner::placeholder {
  color: rgba(255, 255, 255, 0.5) !important;
}

.login-form .el-icon {
  color: rgba(255, 255, 255, 0.6) !important;
}







.tech-canvas {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: block;
}

.tech-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  pointer-events: none;
}

.tech-overlay::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 2px;
  background: linear-gradient(90deg,
    transparent 0%,
    rgba(100, 200, 255, 0.8) 50%,
    transparent 100%
  );
  animation: scanLine 4s linear infinite;
}

@keyframes scanLine {
  0% {
    left: -100%;
    top: 20%;
  }
  25% {
    left: 100%;
    top: 20%;
  }
  26% {
    left: -100%;
    top: 60%;
  }
  50% {
    left: 100%;
    top: 60%;
  }
  51% {
    left: -100%;
    top: 80%;
  }
  75% {
    left: 100%;
    top: 80%;
  }
  76% {
    left: -100%;
    top: 40%;
  }
  100% {
    left: 100%;
    top: 40%;
  }
}

.tech-grid {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-image:
    linear-gradient(rgba(100, 200, 255, 0.03) 1px, transparent 1px),
    linear-gradient(90deg, rgba(100, 200, 255, 0.03) 1px, transparent 1px);
  background-size: 50px 50px;
  animation: gridMove 20s linear infinite;
}

@keyframes gridMove {
  0% { transform: translate(0, 0); }
  100% { transform: translate(50px, 50px); }
}

.tech-particles {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-image:
    radial-gradient(circle at 10% 20%, rgba(100, 200, 255, 0.1) 1px, transparent 1px),
    radial-gradient(circle at 90% 30%, rgba(0, 150, 255, 0.08) 1px, transparent 1px),
    radial-gradient(circle at 20% 80%, rgba(100, 200, 255, 0.06) 1px, transparent 1px),
    radial-gradient(circle at 80% 70%, rgba(0, 150, 255, 0.1) 1px, transparent 1px);
  background-size: 200px 200px, 150px 150px, 180px 180px, 160px 160px;
  animation: particleFloat 15s ease-in-out infinite;
}

@keyframes particleFloat {
  0%, 100% {
    transform: translate(0, 0) rotate(0deg);
    opacity: 0.6;
  }
  50% {
    transform: translate(20px, -20px) rotate(180deg);
    opacity: 1;
  }
}



/* 响应式设计 */
@media (max-width: 768px) {
  .login-form-wrapper {
    padding: 20px;
  }

  .login-form-container {
    max-width: 100%;
    margin: 20px 0;
    padding: 35px;
  }
}
</style>
